package com.jsz.peini.controller.share;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.jsz.peini.bean.activity.ActivityInfo;
import com.jsz.peini.bean.app.SysConfig;
import com.jsz.peini.bean.comm.AppVersion;
import com.jsz.peini.bean.seller.SellerDiscount;
import com.jsz.peini.bean.seller.SellerInfo;
import com.jsz.peini.bean.task.TaskInfo;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.util.CommonUtils;
import com.jsz.peini.common.util.DateTimeUtils;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.mapper.activity.ActivityInfoMapper;
import com.jsz.peini.mapper.app.SysConfigMapper;
import com.jsz.peini.mapper.comm.AppVersionMapper;
import com.jsz.peini.mapper.label.LabelUserMapper;
import com.jsz.peini.mapper.seller.SellerInfoMapper;
import com.jsz.peini.mapper.task.TaskInfoMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.service.advertise.AdvertiseService;
import com.jsz.peini.service.seller.SellerInfoService;

/**
 * @author Han Guohong
 * @version 2017-3-8 上午10:40:03
 * 分享h5页面
 */
@Controller
@RequestMapping("/share")
public class ShareController {
	private static final Logger logger = LoggerFactory.getLogger(ShareController.class);
	@Resource
	private SellerInfoMapper sellerInfoMapper;
	@Resource
	private SellerInfoService sellerInfoService;
	@Resource
	private AdvertiseService advertiseService;
	@Resource
	private AppVersionMapper appVersionMapper;
	@Resource
	private TaskInfoMapper taskInfoMapper;
	@Resource
	private UserInfoMapper userInfoMapper;
	@Resource
	private LabelUserMapper labelUserMapper;
	@Resource
	private SysConfigMapper sysConfigMapper;
	@Resource
	private ActivityInfoMapper activityInfoMapper;
	
	@ResponseBody
	@RequestMapping(value = "/appVersionUpdate",produces="text/plain;charset=UTF-8")
	public String appVersionUpdate(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "versionNo") Integer versionNo,
			@RequestParam(value = "type") Integer type   //1 android;2ios
			) throws JsonGenerationException, JsonMappingException, IOException{
		
		JSONObject object = new JSONObject();
		JSONObject versionObj = new JSONObject();
		
		try{
			if((type == null || type == 0) || (versionNo == null || versionNo == 0)){
				object.put("resultCode", Constants.FAIL);
				object.put("resultDesc", "");
				object.put("data", "");
			}else{
				AppVersion vu = appVersionMapper.selectByPrimaryKey(type);
				if(vu == null){
					object.put("resultCode", Constants.FAIL);
					object.put("resultDesc", "");
					object.put("data", "");
				}else{
					if(type == 1){
						int version = vu.getVersionNo();
						if(version > versionNo){
							versionObj.put("version", String.valueOf(version));
							versionObj.put("address", vu.getServerUrl());
							versionObj.put("forceUpdate", vu.getForceUpdate());
							object.put("resultCode", Constants.SUCCESS);
							object.put("resultDesc", "");
							object.put("data", versionObj);
						}else{
							object.put("resultCode",Constants.FAIL);
							object.put("resultDesc", "");
							object.put("data", new JSONObject());
						}
					}else if(type == 2){
						/*versionObj.put("version", String.valueOf(vu.getVersionNo()));
						versionObj.put("address", vu.getServerUrl());
						object.put("resultCode", Constants.SUCCESS);
						object.put("resultDesc", "");
						object.put("data", versionObj);*/
						int version = vu.getVersionNo();
						if(version == versionNo){
							SysConfig config = sysConfigMapper.selectByPrimaryKey(3);
							Date opTime = DateTimeUtils.formatString2Date(config.getConval(), "yyyyMMdd");
							if(opTime.after(new Date())){
								versionObj.put("version", String.valueOf(version));
								versionObj.put("address", vu.getServerUrl());
								versionObj.put("forceUpdate", "");
								versionObj.put("opVal", 0);
								object.put("resultCode", 100);
								object.put("resultDesc", "");
								object.put("data", versionObj);
							}else {
								versionObj.put("version", String.valueOf(version));
								versionObj.put("address", vu.getServerUrl());
								versionObj.put("forceUpdate", "");
								versionObj.put("opVal", 1);
								object.put("resultCode", 100);
								object.put("resultDesc", "");
								object.put("data", versionObj);
							}
						}else if(version > versionNo){
							versionObj.put("version", String.valueOf(version));
							versionObj.put("address", vu.getServerUrl());
							versionObj.put("forceUpdate", vu.getForceUpdate().toString());
							versionObj.put("opVal", 1);
							object.put("resultCode", Constants.SUCCESS);
							//object.put("resultCode", 100);
							object.put("resultDesc", "");
							object.put("data", versionObj);
						}else{
							object.put("resultCode",Constants.FAIL);
							object.put("resultDesc", "");
							object.put("data", new JSONObject());
						}
					}
				}
			}
		}catch(Exception e){
			object.put("resultCode", Constants.EXCEPTION);
			object.put("resultDesc", e.toString());
			object.put("data", "");
		}
		
		return object.toString();
	}

	/**
	 * 图片分享链接
	 * @author Han Guohong
	 * @param request
	 * @param imgUrl
	 * @return
	 */
	@RequestMapping("/imgDetail")
	public String imgDetail(HttpServletRequest request,
			@RequestParam(value="imgUrl") String imgUrl
			){
		request.setAttribute("imgUrl", imgUrl);
		return "share/imgDetail";
	}
	
	/**
	 * 店铺详情
	 * @author Han Guohong
	 * @param request
	 * @param sellerId
	 * @return
	 */
	@RequestMapping("/sellerDetail")
	public String sellerDetail(HttpServletRequest request,
			@RequestParam(value="sellerId") String sellerId
			){
		
		try {
			if(StringUtils.isBlank(sellerId)){
				return null;
			}
			SellerInfo sellerInfo = sellerInfoMapper.selectByPrimaryKey(Integer.parseInt(sellerId));
			
			List<LinkedHashMap<String,Object>> advertiseList=advertiseService.getAdvertise(3);
			
			request.setAttribute("info", sellerInfo);
			request.setAttribute("ads", advertiseList);
			
			// 设置金币折扣信息
			Date d = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
			String dateStr = sdf.format(d);
			SellerDiscount sellerDiscount = new SellerDiscount();
			sellerDiscount.setSellerInfoId(Integer.parseInt(sellerId));
			sellerDiscount.setNowNum(CommonUtils.getWeekNum());
			sellerDiscount.setNowTime(dateStr);
			SellerDiscount discountMap = sellerInfoService
					.getSellerDiscount(sellerDiscount);
			if (discountMap != null) {
				if(discountMap.getGoldNum() != null && discountMap.getGoldNum() != 100){
					request.setAttribute("goldC", discountMap.getGoldNum());
				}
				if(discountMap.getWeixinNum() != null && discountMap.getWeixinNum() != 100){
					request.setAttribute("wxC", discountMap.getWeixinNum());
				}
				if(discountMap.getZfbNum() != null && discountMap.getZfbNum() != 100){
					request.setAttribute("aliC", discountMap.getZfbNum());
				}
			}
			
			// 设置优惠券信息
			List<HashMap<String, Object>> couponList = sellerInfoService.getSellerCoupons(Integer.parseInt(sellerId));
			if (couponList.size() > 0) {
				StringBuffer str = new StringBuffer();
				for (HashMap<String, Object> couponMap : couponList) {
					str.append(couponMap.get("couponName") + ",");
				}
				request.setAttribute("youhui", str.toString().substring(0,str.length() - 1));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return "share/sellerDetail";
	}
	
	@RequestMapping("/taskDetail")
	public String taskDetail(HttpServletRequest request,
			@RequestParam(value="taskId") String taskId
			){
		
		try {
			TaskInfo taskInfo = taskInfoMapper.selectByPrimaryKey(Integer.parseInt(taskId));
			
			UserInfo userInfo = userInfoMapper.selectByPrimaryKey(taskInfo.getUserId());
			
			taskInfo.setUserPhone(userInfo.getUserLogin().getUserName());
			taskInfo.setNickName(userInfo.getNickname());
			taskInfo.setImageHead(userInfo.getImageHead());
			taskInfo.setSex(userInfo.getSex() == null ? 3 : userInfo.getSex());
			taskInfo.setAge(userInfo.getAge());
			taskInfo.setGoldList(userInfo.getGoldList());
			taskInfo.setBuyList(userInfo.getBuyList());
			taskInfo.setIntegrityList(userInfo.getIntegrityList());
			taskInfo.setReputation(userInfo.getReputation());
			
			List<LinkedHashMap<String, Object>> userLabel = labelUserMapper.selectLabelUserByUserInfoId((String) taskInfo.getUserId());
			taskInfo.setUserLabel(userLabel);
			
			request.setAttribute("info", taskInfo);
			
			SellerInfo sellerInfo = sellerInfoMapper.selectByPrimaryKey(taskInfo.getSellerInfoId());
			request.setAttribute("seller", sellerInfo);
			
			request.setAttribute("target", PeiniUtils.yetaiMap.get(taskInfo.getSellerSmallType().toString()).getCodesContent());
			
			List<LinkedHashMap<String,Object>> advertiseList=advertiseService.getAdvertise(3);			
			request.setAttribute("ads", advertiseList);
			
		}catch(Exception e){
			logger.error(e.getMessage(),e);
		}
		return "share/taskDetail";
	}
	
	/**
	 * 获取活动分享内容
	 * @author Han Guohong
	 * @param request
	 * @param acId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getActivityShare")
	public Object getActivityShare(HttpServletRequest request,
			@RequestParam(value="id") String acId
			){
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		try {
			ActivityInfo activityInfo = activityInfoMapper.selectByPrimaryKey(acId);
			
			LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
			map.put("shareTitle", "陪你APP正在开启"+activityInfo.getAcTitle()+"活动，快去报名参加吧>>>");
			map.put("shareContent", "活动时间"+DateTimeUtils.formatDateTime2LongString(activityInfo.getStartTime())+"，活动地点" +
					activityInfo.getAcAddress()+"，活动内容"+activityInfo.getAcDesc());
			infoMap.put("data",map);
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", Constants.SUCCESS_DESC);
			
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.FAIL);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
		}
		
		return infoMap;
	}
}
